package com.xpec.c4.db.dao;

import java.util.Collection;
import java.util.Stack;

import org.hibernate.Session;

import com.xpec.c4.db.basic.BasicGameDAO;
import com.xpec.c4.db.hibernate.manager.HibernateManager;
import com.xpec.c4.db.model.basic.BasicModel;

/**
 * 辅助的DAO
 * 
 * @author Bany
 *
 */
public class HelperDAO extends BasicGameDAO {
	
	private static ThreadLocal<Stack<BasicModel>> deleteEntitys=new ThreadLocal<Stack<BasicModel>>();
	
	/**
	 * 清除多余的MODEL层数据
	 */
	public static void deleteModels(){
		Stack<BasicModel> entitys=deleteEntitys.get();
		if(entitys==null ){
			return;
		}
		Session session=HibernateManager.getSession();
		HibernateManager.txBegin();
		while(!entitys.isEmpty()){
			Object obj=entitys.pop();
			if(obj!=null){
				session.delete(obj);
			}
		}
		HibernateManager.txCommitFailRollbackClearSession();
	}
	
	/**
	 * 
	 * 
	 * @param obj
	 *
	 * @2011-9-30 下午06:22:17
	 */
	public static void addDeleteEntity(BasicModel obj){
		Stack<BasicModel> entitys = getDeleteEntitys();
		entitys.push(obj);
	}
	
	public static void addDeleteEntitys(Collection<? extends BasicModel> objs){
		Stack<BasicModel> entitys = getDeleteEntitys();
		
		for (BasicModel basicModel : objs) {
			entitys.push(basicModel);
		}

	}

	private static Stack<BasicModel> getDeleteEntitys() {
		Stack<BasicModel> entitys=deleteEntitys.get();
		if(entitys==null ){
			entitys=new Stack<BasicModel>();
			deleteEntitys.set(entitys);
		}
		return entitys;
	}
	
	/**
	 * 待删除的缓存是否为空
	 * @return
	 */
	public static boolean isEmpty(){
		Stack<BasicModel> entitys=deleteEntitys.get();
		if(entitys==null){
			return true;
		}
		return entitys.isEmpty();
	}

}
